#!/usr/bin/python

"""
Author:			Jimmy Saw
Date modified:	06-18-2012

Description:    This script can concatenate individual fasta files edited with
                Gblocks and convert them to phylip format needed by RAxML. It
                expects 2 list files: one contains a list of bioproject ids and
                the other a list of genes.

Usage:          dissertation_ConcatConvertMSA.py <genes list> <org list>

Example:        dissertation_ConcatConvertMSA.py r43.list cyano.list

Note:           

"""

import sys
import re
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import generic_protein

genelistfile = open(sys.argv[1], "rU")
genelist = genelistfile.readlines()

orglistfile = open(sys.argv[2], "rU")
orglist = orglistfile.readlines()

orgdict = {}

for i in orglist:
    o = i.strip()
    orgdict[o] = []

protlist = []

for line in genelist:
    l = line.strip()
    seqs = SeqIO.parse(l+".align.muscle-gb", "fasta")
    for seq in seqs:
        if seq.id in orgdict:
            orgdict[seq.id].append(str(seq.seq))

for k, v in orgdict.iteritems():
    aa = "".join(v[0:])
    tmpseqrec = SeqRecord(Seq(aa, generic_protein), id=k, description="")
    protlist.append((k, aa))

for j in protlist:
    seqid = j[0]
    seq = j[1]
    tmpseqrec = SeqRecord(Seq(seq, generic_protein), id=seqid, description="")
    outfaa = seqid + ".concat.faa"
    SeqIO.write(tmpseqrec, outfaa, "fasta")

genelistfile.close()
orglistfile.close()

